package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhHouseDetailMapper;
import com.jwsoft.manager.core.dao.mapper.EdutHouseDetailMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduHouseDetailMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduHouseDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author wangtao
 * @since 2022-12-01
 */
@Service
@Slf4j
public class EduHouseDetailServiceImpl extends ServiceImpl<EduHouseDetailMapper, EduHouseDetail> implements EduHouseDetailService , TableService {

    @Autowired
    private EduhHouseDetailMapper hHouseDetailMapper;

    @Autowired
    private EdutHouseDetailMapper tHouseDetailMapper;

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    private static final String HOUSE_DETAIL_TABLE = "edu_house_detail";

    private static final Integer PAGE_SIZE = 10000;



    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseDetailServiceImpl服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_house_detail迁移" + count + "条数据");
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduHouseDetail> eduHouseDetails =
                    this.baseMapper.selectByYear(optionVO.getYear(),PAGE_SIZE);
            if (eduHouseDetails.size() > 0) {
                List<EduhHouseDetail> hHouseDetails = eduHouseDetails.stream().map(eduHouseDetail -> {
                    EduhHouseDetail hHouseDetail = new EduhHouseDetail();
                    BeanUtils.copyProperties(eduHouseDetail, hHouseDetail);
                    ;
                    hHouseDetail.setTaskDetailId(taskDetail.getTaskDetailId());
                    hHouseDetail.setEncryptFlag(BoolEnum.FALSE.getType());
                    hHouseDetail.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    hHouseDetail.setCleanFlag(BoolEnum.FALSE.getType());
                    return hHouseDetail;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hHouseDetails, eduHouseDetails.size(),optionVO);
                } catch (Exception e) {
                    log.error("edu_house_detail迁移数据发生异常");
                    throw new RuntimeException("EduHouseDetailServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private Integer performDataMigration(List<EduhHouseDetail> hHouseDetails, Integer count, DataTaskDetailOptionVO optionVO) {
        Integer result = transactionTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus status) {
                try {
                    //1.数据迁移到历史表
                    int saveHCount = hHouseDetailMapper.saveBatch(hHouseDetails);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_house_detail数据销毁成功！销毁数量：" + count);
                    return count;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
        //返回处理的结果数量
        return result;
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseDetailServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count =  0;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduhHouseDetail> hHouseDetailList =
                    this.baseMapper.selectEncryptionByYear(optionVO.getYear(), optionVO.getTaskDetailId(),PAGE_SIZE);
            for (EduhHouseDetail eduhHouseDetail : hHouseDetailList) {
                try {
                    //加密
                    this.encrypt(eduhHouseDetail);
                    eduhHouseDetail.setEncryptTime(new Date());
                    eduhHouseDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    eduhHouseDetail.setEncryptRemarks("加密成功");
                    eduhHouseDetail.setEncryptFlag(BoolEnum.TRUE.getType());
                    //保存到数据库，可能成功，可能失败，失败就不加密
                    try {
                        hHouseDetailMapper.updateById(eduhHouseDetail);
                    }catch (Exception dbException) {
                        log.error("更新数据库失败，ID: {}, 错误信息: {}", eduhHouseDetail.getHouseDetailId(), dbException.getMessage());
                        // 不抛出异常，仅记录日志
                        continue;
                    }

                } catch (Exception e) {
                    //解密
                    this.decrypt(eduhHouseDetail);
                    eduhHouseDetail.setEncryptTime(new Date());
                    eduhHouseDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    eduhHouseDetail.setEncryptFlag(BoolEnum.FALSE.getType());
                    eduhHouseDetail.setEncryptRemarks("加密失败"+e.getMessage());
                    hHouseDetailMapper.updateById(eduhHouseDetail);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    /**
     * 历史数据解密
     * @param eduhHouseDetail
     */
    private void decrypt(EduhHouseDetail eduhHouseDetail) {
        if (StringUtils.isNotBlank(eduhHouseDetail.getRealProperty())){
            eduhHouseDetail.setRealProperty(CommonSecureUtil.sm4Decrypt(eduhHouseDetail.getRealProperty()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getObligee())){
            eduhHouseDetail.setObligee(CommonSecureUtil.sm4Decrypt(eduhHouseDetail.getObligee()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getIdcard())){
            eduhHouseDetail.setIdcard(CommonSecureUtil.sm4Decrypt(eduhHouseDetail.getIdcard()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getFullName())){
            eduhHouseDetail.setFullName(CommonSecureUtil.sm4Decrypt(eduhHouseDetail.getFullName()));
        }
    }

    /**
     * 历史数据加密
     * @param eduhHouseDetail
     */
    private void encrypt(EduhHouseDetail eduhHouseDetail) {
        if (StringUtils.isNotBlank(eduhHouseDetail.getRealProperty())){
            eduhHouseDetail.setRealProperty(CommonSecureUtil.sm4Encrypt(eduhHouseDetail.getRealProperty()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getObligee())){
            eduhHouseDetail.setObligee(CommonSecureUtil.sm4Encrypt(eduhHouseDetail.getObligee()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getIdcard())){
            eduhHouseDetail.setIdcard(CommonSecureUtil.sm4Encrypt(eduhHouseDetail.getIdcard()));
        }
        if (StringUtils.isNotBlank(eduhHouseDetail.getFullName())){
            eduhHouseDetail.setFullName(CommonSecureUtil.sm4Encrypt(eduhHouseDetail.getFullName()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseDetailServiceImpl服务的dataDestruction来进行处理数据清洗");
        Boolean cleanFlag =
            detailService.verifyDestructionByTable(taskDetail.getYear(),HOUSE_DETAIL_TABLE,taskDetail.getTaskId());
        if (!cleanFlag){
            //主表还未执行数据清洗，
            throw new AppException(HOUSE_DETAIL_TABLE+"表还未执行完数据清洗，"+taskDetail.getHandleTable()+"无法进行清洗");
        }
        //查询副表中要清洗的数据
        List<EduhHouseDetail> hHouseDetails =
            this.baseMapper.queryCleanData(taskDetail.getTaskDetailId(),taskDetail.getYear());
        Integer cleanCount = hHouseDetails.size();
        if (cleanCount != 0){
            try {
                this.preformDataClean(hHouseDetails,cleanCount);
            } catch (Exception e) {
                log.error("eduh_house_detail数据清洗发生异常");
                throw new RuntimeException("EduHouseDetailServiceImpl:" + e);
            }
        }
        return cleanCount;
    }

    private void preformDataClean(List<EduhHouseDetail> hHouseDetails, Integer cleanCount) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    List<EdutHouseDetail> tHouseDetailList = hHouseDetails.stream().map(item -> {
                        EdutHouseDetail tHouseDetail = new EdutHouseDetail();
                        BeanUtils.copyProperties(item, tHouseDetail);
                        tHouseDetail.setCleanFlag(BoolEnum.TRUE.getType());
                        return tHouseDetail;
                    }).collect(Collectors.toList());
                    tHouseDetailMapper.saveBatch(tHouseDetailList);
                    Integer count = 0;
                    for (EduhHouseDetail hHouseDetail : hHouseDetails) {
                        count ++;
                        hHouseDetailMapper.deleteHistoryById(hHouseDetail.getHouseDetailId());
                    }
                    if (count != cleanCount){
                        throw new AppException("要清洗的数据为："+cleanCount+",清洗的数据为："+count+"数据量不一致，请检查后重试！");
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void tempDataDestruction() {
        System.out.println("空闲数据销毁");
    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hHouseDetailMapper.selectCount(new QueryWrapper<EduhHouseDetail>().lambda().eq(EduhHouseDetail::getTaskDetailId, optionVO.getTaskDetailId())));
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        for (int i = 0; i < totalPages; i++) {
            //将历史表数据查询出来
            List<EduhHouseDetail> hHouseDetailList =
                    hHouseDetailMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutHouseDetail> tHouseDetailList = hHouseDetailList.stream().map(eduhHouseDetail -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhHouseDetail.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(eduhHouseDetail);
                }
                EdutHouseDetail edutHouseDetail = new EdutHouseDetail();
                BeanUtils.copyProperties(eduhHouseDetail, edutHouseDetail);
                return edutHouseDetail;
            }).collect(Collectors.toList());
            tHouseDetailMapper.saveBatch(tHouseDetailList);
            currentPage ++;
        }
    }
}
